/**
 * Created by zhangqingxi on 2017/3/15.
 */


$(function () {

    initDept();


    //表单提交
    $('#departmentSave').on('click',function () {

        layer.confirm('是否确定保存？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $('#departmentForm').form('submit', {
                url: ROOT_PATH+'/permission/department/edit.shtml',
                onSubmit: function (param) {
                    var isValid = $(this).form('validate');
                    if (!isValid) {
                        layer.close(index);
                        layer.msg("请正确填写表单")
                    }
                    return $(this).form('validate');
                },
                success: function (result) {
                    var data = $.parseJSON(result);
                    if(data.success){
                        window.parent.closeLayer(data);
                    }else{
                        layer.msg(data.message,{time:1000,icon:2});
                    }
                }
            });
        });

    });
    //参数清空
    $('#departmentReset').on('click',function () {
        $('#departmentForm').form('reset');
    });

    $.extend($.fn.validatebox.defaults.rules, {
        checkCode : {
            validator: function (value) {
                var checkR=$.ajax({
                    async : false,
                    cache : false,
                    type : 'post',
                    url : ROOT_PATH+'/permission/department/findByCodeAndId.shtml',
                    data : {
                        code:value,id:$('#deptId').val()
                    }
                }).responseText;
                var dataObj=$.parseJSON(checkR);//转换为json对象
                var flag=dataObj.success==true;
                if(!flag){
                    $('#code_err').css('display','block');
                }else {
                    $('#code_err').css('display','none');
                }
                return flag;
            },
            message: '当前部门编号已存在！'
        }
    });
});

function initDept() {

    //初始化下拉树
    $('#parentDepartmentId').combotree({
        url: ROOT_PATH+'/permission/department/getDepartmentTree.shtml?parentId=0',
        required: true,
        //readonly:readonly,
        onSelect:function (r) {
            generateDeptCode(r.id)
        }
    });

}
/**
 * 自动生成部门编码
 */
function generateDeptCode(parentId) {
    $.ajax({
        type : 'post',
        dataType:'json',
        url : ROOT_PATH+'/permission/department/findCodeByParentId.shtml',
        data : {
            parentId:parentId
        },
        success:function (data) {
            $('#code').textbox('setValue',data)
        }
    })

}
